#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'ben'
__mtime__ = '4/28/16'
"""

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, DateTime, Float
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy import desc

from mysqlFactory.database_url import CDataBaseUrl

Base = declarative_base()
db_handler = CDataBaseUrl('mysql')
MySql_Uri = {
    'host': '192.168.51.32',
    'port': 3306,
    'database': 'wydata',
    'user': 'root',
    'password': 'datagather'
}

db_url = db_handler.make_db_url(MySql_Uri)
engine = create_engine(db_url, encoding='utf-8', echo=True, pool_recycle=5)
Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)


class CFdfsORM(object):

    def __init__(self):
        self.session = Session()

    def get_data(self, file_id):
        """
        :param file_id: 文件ID
        """
        result = {}

        if not file_id:
            return


        try:
            record_list = self.session.query(CFileList).filter(CFileList.file_id == file_id).order_by(
                desc(CFileList.id)).first()

            if record_list:
                kv = record_list._sa_instance_state.dict
                if isinstance(kv, dict):
                    if kv.has_key('_sa_instance_state'):
                        kv.pop('_sa_instance_state')

                result = kv

        except Exception as e:
            raise e
        finally:
            self.session.close()

        return result


    def get_all_data(self, file_id):
        """
        :param file_id:文件ID
        """
        result = []

        try:
            if not file_id:
                return

            record_list = self.session.query(CFileList).filter(CFileList.file_id == file_id).order_by(
                desc(CFileList.id)).all()

            for record in record_list:

                kv = record._sa_instance_state.dict
                if isinstance(kv, dict):
                    if kv.has_key('_sa_instance_state'):
                        kv.pop('_sa_instance_state')

                result.append(kv)
        except Exception as e:
            raise e
        finally:
            self.session.close()

        return result

    def insert_data(self, file_upload_dict):
        if not file_upload_dict:
            return

        try:
            new_file = CFileList()
            if isinstance(file_upload_dict, dict):
                new_file.file_id = file_upload_dict.get('file_id')
                new_file.remote_file_id = file_upload_dict.get('remote_file_id')
                new_file.ext = file_upload_dict.get('ext')
                new_file.storage_ip = file_upload_dict.get('storage_ip')
                new_file.group_name = file_upload_dict.get('group_name')
                new_file.file_size = file_upload_dict.get('file_size')
                new_file.local_file_name = file_upload_dict.get('local_file_name')
                new_file.status = file_upload_dict.get('status')
                new_file.create_time = file_upload_dict.get('create_time')
                new_file.storage_port = file_upload_dict.get('storage_port', 8080)

            self.session.add(new_file)
            self.session.flush()
            self.session.commit()
        except Exception as e:
            raise e
        finally:
            self.session.close()


class CFileList(Base):
    '''
    小文件系统表
    '''
    __tablename__ = 'tb_file_list'

    id = Column('id', Integer, primary_key=True, autoincrement='ignore_fk')
    file_id = Column('file_id', String, nullable=False)
    remote_file_id = Column('remote_file_id', String, nullable=False)
    ext = Column('ext', String, nullable=False, server_default="html")
    storage_ip = Column('storage_ip', String, nullable=False)
    group_name = Column('group_name', String, nullable=False)
    file_size = Column('file_size', String, nullable=False)
    local_file_name = Column('local_file_name', String, nullable=True)
    status = Column('status', String, nullable=False)
    create_time = Column('create_time', Integer, nullable=False)
    storage_port = Column('storage_port', Integer, nullable=False, server_default="8080")


if __name__ == "__main__":
    new_file_dict = {}

    new_file_dict['file_id'] = 'test'
    new_file_dict['remote_file_id'] = 'ss'
    new_file_dict['status'] = 's'
    new_file_dict['group_name'] = 'group1'
    new_file_dict['storage_ip'] = 'sdas'
    new_file_dict['file_size'] = 'sdada'
    new_file_dict['local_file_name'] = ''
    new_file_dict['create_time'] = 1462332524
    new_file_dict['ext'] = 'txt'

    orm_test = CFdfsORM()
    orm_test.insert_data(new_file_dict)